package cn.tworice.admin.web;


import cn.tworice.common.utils.UploadUtil;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.common.vo.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin/upload")
@Slf4j
@CrossOrigin
public class UploadController {

    @Autowired
    private UploadUtil uploadUtil;

    /**
     * 快捷上传文件接口
     * 返回上传后的地址
     * @author 二饭[tworice@sina.cn][2022/3/2 14:02]
     */
    @PostMapping("upload")
    public RequestResult upload(MultipartFile file) {
        RequestResult result = new RequestResult();
        String path=uploadUtil.uploadFile(file);
        if(path!=null){
            result.setStatus(new StatusCode(200,"上传成功"));
            result.appendData("url",path);
            result.appendData("message","访问时请在该文件路径前加上本服务器地址");
        }else{
            result.setStatus(new StatusCode(204,"上传失败"));
        }
        return result;
    }

    /**
     * 获取文件的Base64编码
     * @param path 文件名称
     * @return java.lang.String Base64编码
     * @author 二饭 [2022/9/24]
     **/
    @GetMapping("download/{path}")
    public String download(@PathVariable String path) {
        String filePath=System.getProperty("user.dir")+"/target/classes/static/upload/"+path;
        return uploadUtil.getBase64(filePath);
    }
}
